/**
 * 
 */
package com.cnhaimei.vod.net;

import java.net.DatagramPacket;
import java.net.InetSocketAddress;
import java.util.ArrayDeque;

import android.util.Log;

import com.cnhaimei.com.VODLog;
import com.cnhaimei.net.UDPSocket;
import com.cnhaimei.vod.logic.EventsManager;
import com.cnhaimei.vod.util.Util;

/**
 * VOD数据库查询服务器心跳接者
 * 
 * @author jin001.wu@gmail.com <br>
 * @date 2011-7-26
 * 
 */
public class DQHeart extends UDPSocket {
	private final static Object lock = new Object();
	private final static String TAG = "DQHeartReceiver";
	public final static int PORT = 2027;
	private static String DEF = "";//"10.0.0.9";//"10.0.0.9";

	private static ArrayDeque<String>  queue = new ArrayDeque<String>(10);

	public DQHeart() {
		super(PORT, 1024, 1024);
	}

	@Override
	protected void onReceive(DatagramPacket mPacket) {
		// mPacket.getAddress().getHostAddress();
		// mPacket.getSocketAddress()
		String ip = mPacket.getAddress().getHostAddress();//mPacket.getAddress().getHostName();
		if (ip.equals("bogon")) {
			Log.e(TAG, "receive ip = bogon, get other");
			if (Util.VLOG) {
				VODLog.e(TAG, "receive ip = bogon, get other");
			}		
			try {
				ip = ((InetSocketAddress)mPacket.getSocketAddress()).getAddress().getHostAddress();				
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		Log.e(TAG, "receive ip " + ip);
		synchronized (lock) {
			queue.add(ip);
		}
		if (ip != null && !DEF.equals(ip)) {
			if (Util.VLOG) {
				VODLog.e(TAG, "dqheart onReceive, ip = " + ip);
			}
			if (ip.equals("bogon")) {
				return;
			}
			DEF = ip;
			EventsManager.G().sendEvent(EventsManager.Event.CONNECTING, id, true);			
		}
	}
	
	protected void onConnected(boolean isSuc) {
		EventsManager.G()
				.sendEvent(EventsManager.Event.CONNECTING, id, isSuc);
	}
	
	public static String getVODServerIP() {
		String ip = null;
		synchronized (lock) {
			ip = queue.pollLast();
			if (ip == null) {
				if (Util.DEMO || Util.TEST) {
					return DEF;
				}
				return null;// 
			}
		}

		return ip;
	}
	
	
	public void start() {
		if (!isRun()) {
			new Thread(this).start();
		}
	}
	

}
